import React, { useState } from "react";
import {
  Card,
  Tabs,
  Form,
  Input,
  Button,
  Avatar,
  Upload,
  message,
  Switch,
  Select,
  Divider,
  Space,
  Typography,
  Row,
  Col,
  Alert,
  Modal,
  List,
  Tag,
} from "antd";
import {
  UserOutlined,
  UploadOutlined,
  BellOutlined,
  SecurityScanOutlined,
  SettingOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  DeleteOutlined,
  KeyOutlined,
} from "@ant-design/icons";
import { useUser } from "../../contexts/UserContext";
import styled from "styled-components";

const { TabPane } = Tabs;
const { Title, Text } = Typography;
const { Password } = Input;

const SettingsContainer = styled.div`
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
`;

const AvatarContainer = styled.div`
  text-align: center;
  margin-bottom: 24px;
`;

const SettingItem = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
`;

const Settings: React.FC = () => {
  const { user, refreshAuth } = useUser();
  const [loading, setLoading] = useState(false);
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [changePasswordVisible, setChangePasswordVisible] = useState(false);

  // 表单实例
  const [profileForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [notificationForm] = Form.useForm();

  // 状态管理
  const [notifications, setNotifications] = useState({
    email: true,
    browser: true,
    mobile: false,
    courseUpdates: true,
    examReminders: true,
    discussionReplies: true,
    systemMessages: true,
  });

  const [systemSettings, setSystemSettings] = useState({
    theme: "light",
    language: "zh-CN",
    autoSave: true,
    showOnlineStatus: true,
  });

  // 处理个人信息更新
  const handleProfileUpdate = async (values: any) => {
    try {
      setLoading(true);
      console.log("更新个人信息:", values);

      // TODO: 调用更新用户信息的API
      // const { authAPI } = await import("../../services/apiService");
      // await authAPI.updateProfile(values);

      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 刷新用户信息
      await refreshAuth();

      message.success("个人信息更新成功");
    } catch (error) {
      console.error("更新个人信息失败:", error);
      message.error("更新失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  // 处理密码修改
  const handlePasswordChange = async (values: any) => {
    try {
      setLoading(true);
      console.log("修改密码:", { currentPassword: "***", newPassword: "***" });

      // TODO: 调用修改密码的API
      // const { authAPI } = await import("../../services/apiService");
      // await authAPI.changePassword({
      //   currentPassword: values.currentPassword,
      //   newPassword: values.newPassword
      // });

      await new Promise((resolve) => setTimeout(resolve, 1000));

      message.success("密码修改成功");
      setChangePasswordVisible(false);
      passwordForm.resetFields();
    } catch (error) {
      console.error("修改密码失败:", error);
      message.error("密码修改失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  // 处理头像上传
  const handleAvatarUpload = async (file: File) => {
    try {
      setLoading(true);
      console.log("上传头像:", file.name);

      // TODO: 调用上传头像API
      // const { fileAPI } = await import("../../services/apiService");
      // const uploadResult = await fileAPI.uploadAvatar(file);
      // await authAPI.updateProfile({ avatar: uploadResult.url });

      // 模拟上传
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 刷新用户信息
      await refreshAuth();

      message.success("头像上传成功");
    } catch (error) {
      console.error("头像上传失败:", error);
      message.error("头像上传失败");
    } finally {
      setLoading(false);
    }
  };

  // 处理通知设置更新
  const handleNotificationUpdate = (key: string, value: boolean) => {
    setNotifications((prev) => ({
      ...prev,
      [key]: value,
    }));
    message.success("设置已保存");
  };

  // 处理系统设置更新
  const handleSystemSettingUpdate = (key: string, value: any) => {
    setSystemSettings((prev) => ({
      ...prev,
      [key]: value,
    }));
    message.success("设置已保存");
  };

  // 账户安全操作
  const handleAccountSecurity = (action: string) => {
    Modal.confirm({
      title: `确认${action}？`,
      content: `此操作将${action}，确定要继续吗？`,
      onOk: async () => {
        try {
          setLoading(true);
          await new Promise((resolve) => setTimeout(resolve, 1000));
          message.success(`${action}成功`);
        } catch (error) {
          message.error(`${action}失败`);
        } finally {
          setLoading(false);
        }
      },
    });
  };

  // 渲染个人资料表单
  const renderProfileForm = () => (
    <Form
      form={profileForm}
      layout="vertical"
      onFinish={handleProfileUpdate}
      initialValues={user || {}}
    >
      <AvatarContainer>
        <Upload
          name="avatar"
          listType="picture-circle"
          showUploadList={false}
          beforeUpload={(file) => {
            handleAvatarUpload(file);
            return false;
          }}
        >
          <Avatar
            size={120}
            icon={<UserOutlined />}
            src={user?.avatar}
            style={{ cursor: "pointer" }}
          />
        </Upload>
        <div style={{ marginTop: 8 }}>
          <Button icon={<UploadOutlined />}>更换头像</Button>
        </div>
      </AvatarContainer>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: "请输入姓名" }]}
          >
            <Input placeholder="请输入真实姓名" />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "请输入正确的邮箱格式" },
            ]}
          >
            <Input placeholder="请输入邮箱地址" />
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: "请输入手机号" },
              { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item name="role" label="角色">
            <Select disabled>
              <Select.Option value="admin">管理员</Select.Option>
              <Select.Option value="teacher">教师</Select.Option>
              <Select.Option value="student">学生</Select.Option>
            </Select>
          </Form.Item>
        </Col>
      </Row>

      {/* 角色特定字段 */}
      {user?.role === "teacher" && (
        <>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="department" label="所属院系">
                <Input placeholder="如：计算机学院" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="title" label="职称">
                <Select placeholder="请选择职称">
                  <Select.Option value="讲师">讲师</Select.Option>
                  <Select.Option value="副教授">副教授</Select.Option>
                  <Select.Option value="教授">教授</Select.Option>
                  <Select.Option value="助教">助教</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="subject" label="主要学科">
            <Input placeholder="如：计算机科学与技术" />
          </Form.Item>
        </>
      )}

      {user?.role === "student" && (
        <>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="studentId" label="学号">
                <Input placeholder="请输入学号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="major" label="专业">
                <Input placeholder="如：计算机科学与技术" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="className" label="班级">
                <Input placeholder="如：计科21-1班" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="grade" label="年级">
                <Select placeholder="请选择年级">
                  <Select.Option value="2021">2021级</Select.Option>
                  <Select.Option value="2022">2022级</Select.Option>
                  <Select.Option value="2023">2023级</Select.Option>
                  <Select.Option value="2024">2024级</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </>
      )}

      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading}>
          保存个人信息
        </Button>
      </Form.Item>
    </Form>
  );

  // 渲染通知设置
  const renderNotificationSettings = () => (
    <div>
      <Title level={4}>通知方式</Title>
      <SettingItem>
        <div>
          <Text strong>邮件通知</Text>
          <br />
          <Text type="secondary">通过邮件接收系统通知</Text>
        </div>
        <Switch
          checked={notifications.email}
          onChange={(checked) => handleNotificationUpdate("email", checked)}
        />
      </SettingItem>

      <SettingItem>
        <div>
          <Text strong>浏览器通知</Text>
          <br />
          <Text type="secondary">在浏览器中显示桌面通知</Text>
        </div>
        <Switch
          checked={notifications.browser}
          onChange={(checked) => handleNotificationUpdate("browser", checked)}
        />
      </SettingItem>

      <SettingItem>
        <div>
          <Text strong>手机推送</Text>
          <br />
          <Text type="secondary">向手机推送重要通知</Text>
        </div>
        <Switch
          checked={notifications.mobile}
          onChange={(checked) => handleNotificationUpdate("mobile", checked)}
        />
      </SettingItem>

      <Divider />

      <Title level={4}>通知内容</Title>
      <SettingItem>
        <div>
          <Text strong>课程更新</Text>
          <br />
          <Text type="secondary">课程内容、资料更新时通知</Text>
        </div>
        <Switch
          checked={notifications.courseUpdates}
          onChange={(checked) =>
            handleNotificationUpdate("courseUpdates", checked)
          }
        />
      </SettingItem>

      <SettingItem>
        <div>
          <Text strong>考试提醒</Text>
          <br />
          <Text type="secondary">考试前提醒和考试相关通知</Text>
        </div>
        <Switch
          checked={notifications.examReminders}
          onChange={(checked) =>
            handleNotificationUpdate("examReminders", checked)
          }
        />
      </SettingItem>

      <SettingItem>
        <div>
          <Text strong>讨论回复</Text>
          <br />
          <Text type="secondary">有人回复我的讨论时通知</Text>
        </div>
        <Switch
          checked={notifications.discussionReplies}
          onChange={(checked) =>
            handleNotificationUpdate("discussionReplies", checked)
          }
        />
      </SettingItem>

      <SettingItem>
        <div>
          <Text strong>系统消息</Text>
          <br />
          <Text type="secondary">系统维护、更新等重要消息</Text>
        </div>
        <Switch
          checked={notifications.systemMessages}
          onChange={(checked) =>
            handleNotificationUpdate("systemMessages", checked)
          }
        />
      </SettingItem>
    </div>
  );

  // 渲染系统设置
  const renderSystemSettings = () => (
    <div>
      <Title level={4}>界面设置</Title>
      <SettingItem>
        <div>
          <Text strong>主题模式</Text>
          <br />
          <Text type="secondary">选择浅色或深色主题</Text>
        </div>
        <Select
          value={systemSettings.theme}
          onChange={(value) => handleSystemSettingUpdate("theme", value)}
          style={{ width: 120 }}
        >
          <Select.Option value="light">浅色</Select.Option>
          <Select.Option value="dark">深色</Select.Option>
          <Select.Option value="auto">跟随系统</Select.Option>
        </Select>
      </SettingItem>

      <SettingItem>
        <div>
          <Text strong>语言设置</Text>
          <br />
          <Text type="secondary">选择界面显示语言</Text>
        </div>
        <Select
          value={systemSettings.language}
          onChange={(value) => handleSystemSettingUpdate("language", value)}
          style={{ width: 120 }}
        >
          <Select.Option value="zh-CN">简体中文</Select.Option>
          <Select.Option value="en-US">English</Select.Option>
        </Select>
      </SettingItem>

      <Divider />

      <Title level={4}>功能设置</Title>
      <SettingItem>
        <div>
          <Text strong>自动保存</Text>
          <br />
          <Text type="secondary">在填写表单时自动保存草稿</Text>
        </div>
        <Switch
          checked={systemSettings.autoSave}
          onChange={(checked) => handleSystemSettingUpdate("autoSave", checked)}
        />
      </SettingItem>

      <SettingItem>
        <div>
          <Text strong>显示在线状态</Text>
          <br />
          <Text type="secondary">让其他用户看到我的在线状态</Text>
        </div>
        <Switch
          checked={systemSettings.showOnlineStatus}
          onChange={(checked) =>
            handleSystemSettingUpdate("showOnlineStatus", checked)
          }
        />
      </SettingItem>
    </div>
  );

  // 渲染账户安全
  const renderSecuritySettings = () => (
    <div>
      <Alert
        message="账户安全"
        description="保护您的账户安全，建议定期更新密码并启用两步验证"
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />

      <Title level={4}>密码安全</Title>
      <SettingItem>
        <div>
          <Text strong>修改密码</Text>
          <br />
          <Text type="secondary">定期更新密码以保护账户安全</Text>
        </div>
        <Button
          icon={<KeyOutlined />}
          onClick={() => setChangePasswordVisible(true)}
        >
          修改密码
        </Button>
      </SettingItem>

      <Divider />

      <Title level={4}>登录记录</Title>
      <List
        dataSource={[
          {
            device: "Chrome 浏览器",
            location: "北京市",
            time: "2024-03-15 14:30",
            current: true,
          },
          {
            device: "手机 App",
            location: "北京市",
            time: "2024-03-14 09:15",
            current: false,
          },
          {
            device: "Chrome 浏览器",
            location: "上海市",
            time: "2024-03-13 16:45",
            current: false,
          },
        ]}
        renderItem={(item) => (
          <List.Item
            actions={
              item.current
                ? [<Tag color="green">当前会话</Tag>]
                : [
                    <Button type="link" danger size="small">
                      移除
                    </Button>,
                  ]
            }
          >
            <List.Item.Meta
              title={item.device}
              description={`${item.location} • ${item.time}`}
            />
          </List.Item>
        )}
      />

      <Divider />

      <Title level={4}>危险操作</Title>
      <SettingItem>
        <div>
          <Text strong type="danger">
            注销账户
          </Text>
          <br />
          <Text type="secondary">永久删除账户和所有相关数据</Text>
        </div>
        <Button
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleAccountSecurity("注销账户")}
        >
          注销账户
        </Button>
      </SettingItem>

      {/* 修改密码弹窗 */}
      <Modal
        title="修改密码"
        open={changePasswordVisible}
        onCancel={() => setChangePasswordVisible(false)}
        footer={null}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handlePasswordChange}
        >
          <Form.Item
            name="currentPassword"
            label="当前密码"
            rules={[{ required: true, message: "请输入当前密码" }]}
          >
            <Password placeholder="请输入当前密码" />
          </Form.Item>

          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: "请输入新密码" },
              { min: 6, message: "密码至少6位" },
            ]}
          >
            <Password placeholder="请输入新密码" />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            label="确认新密码"
            dependencies={["newPassword"]}
            rules={[
              { required: true, message: "请确认新密码" },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue("newPassword") === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error("两次输入的密码不一致"));
                },
              }),
            ]}
          >
            <Password placeholder="请再次输入新密码" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                确认修改
              </Button>
              <Button onClick={() => setChangePasswordVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );

  return (
    <SettingsContainer>
      <Card>
        <Tabs defaultActiveKey="profile" size="large">
          <TabPane
            tab={
              <span>
                <UserOutlined />
                个人资料
              </span>
            }
            key="profile"
          >
            {renderProfileForm()}
          </TabPane>

          <TabPane
            tab={
              <span>
                <BellOutlined />
                通知设置
              </span>
            }
            key="notifications"
          >
            {renderNotificationSettings()}
          </TabPane>

          <TabPane
            tab={
              <span>
                <SettingOutlined />
                系统设置
              </span>
            }
            key="system"
          >
            {renderSystemSettings()}
          </TabPane>

          <TabPane
            tab={
              <span>
                <SecurityScanOutlined />
                账户安全
              </span>
            }
            key="security"
          >
            {renderSecuritySettings()}
          </TabPane>
        </Tabs>
      </Card>
    </SettingsContainer>
  );
};

export default Settings;
